﻿using System;
using System.Windows.Threading;
using NthDownload.Contracts.Plugins.BandwidthProviders;
using NthDownload.Common.Mapping;
using System.ComponentModel;
using System.Threading;

namespace NthDownload.BandwidthProviderPlugins
{
    [MappableObject]
    public class SpeedLimitBandwidthProvider : IBandwidthProvider, INotifyPropertyChanged
    {
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion INotifyPropertyChanged

        #region Class Members

        private static readonly object SyncContext = new object();
        private long _bandwidthBucket;
        private DateTime _lastTakeTimeStamp;

        private string _guid;
        private string _parentGUID;
        private string _name;
        private long _bytesPerSecond;

        #endregion Class Members

        #region Constructor

        public SpeedLimitBandwidthProvider()
        {
            //
            // Set the defaults
            // 
            BytesPerSecond = 200 * 1024;
            _bandwidthBucket = BytesPerSecond;
            _lastTakeTimeStamp = DateTime.Now;
        }

        #endregion Constructor

        #region Properties

        [MappableProperty]
        public string GUID 
        {
            get
            {
                return _guid;
            }
            set
            {
                _guid = value;
                OnPropertyChanged("GUID");
            }
        }

        [MappableProperty]
        public string ParentGUID
        {
            get
            {
                return _parentGUID;
            }
            set
            {
                _parentGUID = value;
                OnPropertyChanged("ParentGUID");
            }
        }

        [MappableProperty]
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        [MappableProperty]
        public long BytesPerSecond
        {
            get
            {
                return _bytesPerSecond;
            }
            set
            {
                _bytesPerSecond = value;
                OnPropertyChanged("BytesPerSecond");
            }
        }

        public bool HasBandwidth
        {
            get { return (BytesPerSecond > 0); }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Takes bandwidth from the provider
        /// </summary>
        /// <param name="desiredChunkSize">The desired amount of bandwidth to be taken.</param>
        /// <returns>The actual amount of bandwidth issued.</returns>
        public int Take(int desiredChunkSize)
        {
            lock (SyncContext)
            {
                DateTime currentTakeTimeStamp = DateTime.Now;

                TimeSpan diffSinceLastTake = currentTakeTimeStamp - _lastTakeTimeStamp;
                if (diffSinceLastTake.TotalSeconds > 1)
                {
                    _bandwidthBucket = BytesPerSecond;
                }

                int returnVal = (_bandwidthBucket > desiredChunkSize) ? desiredChunkSize : (int)_bandwidthBucket;
                _bandwidthBucket = _bandwidthBucket - returnVal;

                if (returnVal > 0)
                {
                    _lastTakeTimeStamp = DateTime.Now;
                }
                else
                {
                    Thread.Sleep(new TimeSpan(0,0,0,1) - diffSinceLastTake);
                }

                return returnVal;
            }
        }

        #endregion Methods
    }
}
